package function;


import com.alibaba.fastjson2.JSONObject;
import net.UDPClient;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;

/**
 * 发送消息给指定用户
 * 发送：
 * {
 * "function":"sendMessage",
 * "targetName":"zyz",       // 目标用户名
 * "data": // 数据  一个JSONObject对象
 * {
 * "type": "text",           // 文本
 * "text": ""哈喽，郑钰哲""    // 文本内容
 * "sender":"dcb"            // 发送者用户名
 * "timestamp":1716979590882 // 时间戳
 * }
 * {
 * "type": "image",           // 图片
 * "image": "base64Image"     // 图片内容，base64编码,String 类型
 * "sender":"dcb"             // 发送者用户名
 * "timestamp":1716979590882  // 时间戳
 * }
 * {
 * "type": "apply",            // 好友申请
 * “sender”: ”zyz”,            // 申请者
 * ”timestamp": 1716979590882, // 时间戳
 * }
 * }
 * 无返回
 **/

public class SendMessage {
    // 发送文本消息
    public static void send(String targetName, String message, String username) {
        JSONObject data = new JSONObject();
        data.put("type", "text");
        data.put("text", message);
        data.put("sender", username);
        data.put("timestamp", System.currentTimeMillis());
        send(data, targetName);
    }

    public static void send(String targetName, ImageIcon icon, String username) {
        Image image = icon.getImage();
        BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
        bufferedImage.getGraphics().drawImage(image, 0, 0, null);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            ImageIO.write(bufferedImage, "jpg", byteArrayOutputStream);
            byte[] imageBytes = byteArrayOutputStream.toByteArray();
            String base64Image = Base64.getEncoder().encodeToString(imageBytes);
            // 发送
            JSONObject data = new JSONObject();
            data.put("type", "image");
            data.put("image", base64Image);
            data.put("sender", username);
            data.put("timestamp", System.currentTimeMillis());
            send(data, targetName);
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    public static void sendApply(String targetName, String username) {
        JSONObject data = new JSONObject();
        data.put("type", "apply");
        data.put("sender", username);
        data.put("timestamp", System.currentTimeMillis());
        send(data, targetName);
    }

    private static void send(JSONObject data, String targetName) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("function", "sendMessage");
        jsonObject.put("targetName", targetName);
        jsonObject.put("data", data);
        UDPClient.send(jsonObject);
    }
}
